package org.vitaliyl.monitoring.server.dao;

import java.util.ArrayList;
import java.util.List;

import org.vitaliyl.monitoring.server.Datastore;
import org.vitaliyl.monitoring.server.beans.MessageDescriptor;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;

public abstract class AMessageDAO {

	public static List<MessageDescriptor> getMessages() {
		Datastore.logger.info("Getting Messages");
	
		Query query = new Query(Datastore.MESSAGE_TYPE);
		PreparedQuery preparedQuery = Datastore.datastore.prepare(query);
	
		List<Entity> entities = preparedQuery.asList(Datastore.DEFAULT_FETCH_OPTIONS);
	
		List<MessageDescriptor> list = new ArrayList<MessageDescriptor>(entities.size());
		for (Entity entity : entities) {
			MessageDescriptor descriptor = MessageDescriptor.fromEntity(entity);
	
			list.add(descriptor);
		}
	
		return list;
	}

	public static MessageDescriptor getMessageDescriptor(String encodedKey) {
		Key key = KeyFactory.stringToKey(encodedKey);
		Entity entity;
		Transaction txn = Datastore.datastore.beginTransaction();
		try {
			entity = Datastore.datastore.get(key);
			MessageDescriptor descriptor = MessageDescriptor.fromEntity(entity);
	
			txn.commit();
			return descriptor;
		} catch (EntityNotFoundException e) {
			Datastore.logger.severe("No entity for key " + key);
			return null;
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
		}
	}

	public static String createMessageDescriptor(MessageDescriptor descriptor) {
		Datastore.logger.info("Storing MessageDescriptor");
		String encodedKey;
		Transaction txn = Datastore.datastore.beginTransaction();
		try {
			Entity entity = MessageDescriptor.toEntity(descriptor);
			Datastore.datastore.put(entity);
			Key key = entity.getKey();
			encodedKey = KeyFactory.keyToString(key);
			Datastore.logger.fine("MessageDescriptor key: " + encodedKey);
			txn.commit();
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
		}
		return encodedKey;
	}

}
